package com.gzyct.m.api.common.sign;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;
import org.springframework.stereotype.Component;

import com.gzyct.m.api.common.intf.req.InterfaceRequest;
import com.gzyct.m.api.common.intf.resp.InterfaceResp;

@Component
public class HmacSigner extends AbstractSigner {	
	@Override
	protected String wrapRequestSignString(String signString, InterfaceRequest ir, String signKey)
			throws Exception {
		return signString;
	}

	@Override
	protected String wrapRespSignString(String signString, InterfaceResp ir, String signKey) throws Exception {
		return signString;
	}

	@Override
	protected String doSign(byte[] bytes) {
		try{
			
			String signKey = threadLocalsignKey.get();
			threadLocalsignKey.remove();
			return digestHMAC(bytes, signKey.getBytes("utf-8")).toUpperCase();
		}catch(Exception e){
			return "";
		}
	}

	@Override
	protected String wrapSignString(String signString, String channelCode, String signType, String signKey)
			throws Exception {
		return signString;
	}
	
	private static String digestHMAC(byte[] src, byte[] secret){
		try{
			SecretKeySpec secretKey = new SecretKeySpec(secret, "HmacSHA256");
			Mac mac = Mac.getInstance(secretKey.getAlgorithm());
			mac.init(secretKey);
			byte[] macData = mac.doFinal(src);
			return byte2HexStr(macData);
		}catch(Exception e){
			return "";
		}
	}

	private static String byte2HexStr(byte[] array){
		if (null == array){
			return "";
		}
		return new String(Hex.encodeHex(array));
	}
}
